package com.lottery.service;

import com.alibaba.fastjson.JSON;
import com.lottery.constant.LotteryConstants;
import com.lottery.event.RetryEvent;
import com.lottery.model.AwardMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * Kafka消息服务
 */
@Service
@Slf4j
public class KafkaMessageService {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private AwardService awardService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void sendAwardMessage(String userId, String awardId) {
        AwardMessage message = new AwardMessage(userId, awardId);
        ListenableFuture<SendResult<String, String>> future =
            kafkaTemplate.send(LotteryConstants.TOPIC_AWARD, JSON.toJSONString(message));

        future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onSuccess(SendResult<String, String> result) {
                log.info("发送消息成功：{}", message);
                System.out.println("发送消息成功：" + message);
            }

            @Override
            public void onFailure(Throwable ex) {
//                log.error("发送消息失败：{}", message, ex);
                System.out.println("发送消息失败：" + message + "   ->>> 失败异常：" + ex);
                eventPublisher.publishEvent(new RetryEvent(this, userId, awardId));
            }
        });
    }

    @KafkaListener(topics = "#{T(com.lottery.constant.LotteryConstants).TOPIC_AWARD}", concurrency = "3")
    public void handleAwardMessage(ConsumerRecord<String, String> record,
                                 Acknowledgment ack) {
        try {
            AwardMessage message = JSON.parseObject(record.value(), AwardMessage.class);
            boolean success = awardService.grantAward(message.getUserId(), message.getAwardId());

            if (success) {
                ack.acknowledge();
            } else {
                kafkaTemplate.send(LotteryConstants.DLQ_TOPIC, record.value());
                ack.acknowledge();
            }
        } catch (Exception e) {
            log.error("处理消息失败：{}", record.value(), e);
            AwardMessage message = JSON.parseObject(record.value(), AwardMessage.class);
            eventPublisher.publishEvent(new RetryEvent(this, message.getUserId(), message.getAwardId()));
        }
    }
}
